<?php
class Backend{
    private $urlbase = DEPLOY_SERVER;
    private $price;


    public function __construct($registry) {
        $this->customer = $registry->get('customer');
        $this->db = $registry->get('db');
        $this->curl = $registry->get('curl');
    }

    private function get_url_items($url_part, $username, $passwd){
        $auth = base64_encode($username . ':' . $passwd);
        $url = $this->urlbase . $url_part;

        $ret = $this->curl->get($url, array(), '', $auth);
        $rets = json_decode($ret, true);

        return $rets;
    }
    //fetch ssh key pair from backend store server....
     public function fetch_app_ssh_key($username, $passwd, $region){
        $url = 'ssh_key_pair';

        $rets = $this->get_url_items($url, $username, $passwd);
		/*
        if (isset($rets['_items'])){
            $items = $rets['_items'];
			return $items;
        }*/
        return $rets;
    }

    public function check_cloud_key_exist($username, $passwd, $keyname){
        $url = 'ssh_key_pair?where=name=="' . $keyname . '"';

        $rets = $this->get_url_items($url, $username, $passwd);

        if (isset($rets['_items'])){
            $items = $rets['_items'];

            if (empty($items[0])){
                return false;
            }else{
                return true;
            }

        }else{
            return false;
        }
    }

    public function  create_cloud_key($username, $passwd, $keyname, $crypto_method, $public_key){
        $url = $this->urlbase . 'ssh_key_pair';

        $auth = base64_encode($username . ':' . $passwd);

        //init params here
        $param = array(
            'username'=>$username,
            'keyname'=>$keyname,
            'crypto_method'=>$crypto_method,
            'public_key'=>$public_key
        );

        $ret = $this->curl->post($url, $param, array(), '', $auth);
        $rets = json_decode($ret, true);
    }

    public  function get_order_form_info($order_form, $username, $passwd){
        if (!$this->customer->isLogged()) {
            $order_info="login First!";
        }
        else{
            $url = DEPLOY_SERVER.'deploy/'. $order_form;

            $auth = base64_encode($username . ':' . $passwd);

            $ret = $this->curl->get($url, array(), '', $auth);
            $rets = json_decode($ret, true);


            $query = $this->db->query("SELECT count(*) as total FROM " . DB_PREFIX . "order_product_deploy WHERE order_id = " . $order_form . "");
            $total=$query->row['total'];
            if($rets){
                if(isset($rets['deploy_output'])){
                    $i=0;
                    $status = '';
                    foreach($rets['deploy_output'] as $array) {
                        $error_info='';
                        $app = $array['app_api'];

                        if (array_key_exists('web_url', $app)) {
                            $apps[$app['app_type']]['http'] = "<a href='" . $app['web_url'] . "' target='_blank'>" . $app['web_url'] . "</a><br/>";
                        }
                        if (array_key_exists('web_redirect_access', $app)) {
                            $apps[$app['app_type']]['http1'] = "<a href='" . $app['web_redirect_access'] . "' target='_blank'>" . $app['web_redirect_access'] . "</a><br/>";
                        }
                        if (array_key_exists('web_work_access', $app)) {
                            $apps[$app['app_type']]['http2'] = "<a href='" . $app['web_work_access'] . "' target='_blank'>" . $app['web_work_access'] . "</a><br/>";
                        }
                        if (array_key_exists('ssh_access', $app)) {
                            $apps[$app['app_type']]['ssh'] = "<a href='" . $app['ssh_access'] . "' target='_blank'>" . $app['ssh_access'] . "</a><br/>";
                        }
                        if (array_key_exists('mstsc_access', $app)) {
                            $apps[$app['app_type']]['mstsc'] = "<a href='" . $app['mstsc_access'] . "' target='_blank'>" . $app['mstsc_access'] . "</a><br/>";
                        }
                        if (array_key_exists('https_url', $app)) {
                            $apps[$app['app_type']]['https'] = "<a href='" . $app['https_url'] . "' target='_blank'>" . $app['https_url'] . "</a><br/>";
                        }
                        if (array_key_exists('status', $app)) {
                            $apps[$app['app_type']]['status'] = $app['status'];
                        }
                        if ($app['status'] == 'failed') {
                            $status = 'failed';
                            $error_info=json_decode($app['content']);
                            $apps[$app['app_type']]['error_text']=$error_info->_issues->parameter;
                        }
                        if ($app['status'] == 'finished'&&$status!='failed') {
                            $i++;
                            if($i==$total){
                                $status = 'finished';
                            }else{
                                $status = 'deploying';
                            }
                        }

                        $order_info['error'][] = $error_info->_issues->parameter;
                    }

                    $order_info['status'] = $status;
                    $order_info['access'] = $apps;

                }else{
                    $order_info['status'] = $rets['status'];
                    $order_info['access'] = '';
                }
            }else{
                $order_info['status'] ='404';
                $order_info['access'] = '';
            }

        }
        return $order_info;
    }

    public function check_app_name_exist($appname, $username, $passwd){
        $url = "app_api?where='name'=='". $appname."'";
        $rets = $this->get_url_items($url, $username, $passwd);
        $ls = $rets['_items'];
        if(empty($ls)){
            return false;
        }
        else{
            //print_r($ls);
            if (isset($ls)){
                foreach($ls as $rec)
                {
                    if ($rec['name'] == $appname){
                        return true;
                    }else{

                    }
                }
            }
        }

        return false;
    }
    //check if hard-disk name exist
    
    public function check_hd_name_exist($region="qingcloud_pek2",$hdname, $username, $passwd){
        //$url = 'hard_disk?where=name=="' . $hdname . '"';
        $url = 'hard_disk?where={"region":"'.$region.'","name":"'.$hdname.'"}';
        $rets = $this->get_url_items($url, $username, $passwd);

        $ret =$rets['_items'];
      
		
        if(empty($ret)){
            return false;
        }
        else{
            
            if (isset($ret)){
                foreach($ret as $rec)
                {
                    if ($rec['name'] == $hdname){
                        return true;
                    }else{
                    }
                }
            }
        }

        return false;
    }

    //������VPC������������������
    public function check_vpc_name_exist($app_id=0,$vpcname, $username, $passwd){
        $url = 'vpc?where=name=="' . $vpcname . '"';

        $rets = $this->get_url_items($url, $username, $passwd);

        $ret = $rets['_items'];

        if(isset($_SESSION['app']['vpc'])){
            foreach($_SESSION['app']['vpc'] as $key => $vpc){
                if(!$key==$app_id){
                    if($vpcname==$vpc['vpc_name']){
                        return true;
                    }
                }
            }
        }

        if (empty($ret)){
            return false;
        }
        else{
            #print_r($ls);
            if (isset($ret)){
                foreach($ret as $rec)
                {
                    if ($rec['name'] == $vpcname){
                        return true;
                    }else{

                    }
                }
            }
        }
        return false;
    }
    //check ssh port if is exist from the vpc
     public function check_ssh_port_exist($region="qingcloud_pek2",$vpcname, $username, $passwd,$port){
        //$url = 'vpc?where=name=="' . $vpcname . '"';
		$url = 'vpc?where={"region":"'.$region.'","name":"'.$vpcname.'"}';
        $rets = $this->get_url_items($url, $username, $passwd);

        $ret = $rets['_items'];

		//print_r($ret);
        if (empty($ret)){
            return false;
        }
        else{
            #print_r($ls);
            if (isset($ret)){
            	foreach($ret as $rec){
            		if ($rec['name'] == $vpcname){
            			if($rec['port_address_translation']){
            				foreach($rec['port_address_translation'] as $key=>$value){
            					if($value['source_port'] == $port){
            						return true;
            					}
            				}

            			}

                    }
            	}

            }
        }
        return false;
    }
    //end of check ssh port if is exist from the vpc

    //������������������������������
    public function check_eip_name_exist($eipname, $username, $passwd){
        $url = 'public_ip?where=name=="' . $eipname . '"';

        $rets = $this->get_url_items($url, $username, $passwd);

        $ret =$rets['_items'];

        if(empty($ret)){
            return false;
        }
        else{
            #print_r($ls);
            if (isset($ret)){
                foreach($ret as $rec)
                {
                    if ($rec['name'] == $eipname){
                        return true;
                    }else{
                    }
                }
            }
        }

        return false;
    }

    //������������������������������
    public function check_subnet_name_exist($app_id=0,$subnetname, $vpcname, $username, $passwd){


        if(isset($_SESSION['app']['subnet'])){
            foreach($_SESSION['app']['subnet'] as $key=> $subnet){
                if(!$key==$app_id){
                    if($subnetname==$subnet['subnet_name']&&$vpcname==$subnet['vpc_name']){
                        return true;
                    }
                }
            }
        }


        $url = 'vpc?where=name=="' . $vpcname . '"';

        $rets = $this->get_url_items($url, $username, $passwd);

        $ret = $rets['_items'];



        if(empty($ret)){
            return false;
        }
        else{
            if (isset($ret)){
                foreach($ret as $rec)
                {
                    if ($rec['name'] == $vpcname){
                        $nets = $rec['vxnet'];
                        foreach($nets as $net){
                            if($net['vxnet_name'] == $subnetname){
                                return true;
                            }
                        }
                        break;
                    }else{
                    }
                }
            }
        }

        return false;
    }

    public function check_subnet_address($app_id=0,$vpcname , $subnetaddr, $username, $passwd){

        if(isset($_SESSION['app']['subnet'])){
            foreach($_SESSION['app']['subnet'] as $key => $subnet){
                if(!$key==$app_id){
                    if($vpcname==$subnet['vpc_name']&&$subnetaddr==$subnet['network']){
                        return true;
                    }
                }
            }
        }


        $url = 'vpc?where=name=="' . $vpcname . '"';

        $rets = $this->vpclist = $this->get_url_items($url, $username, $passwd);
        $ret = $rets['_items'];

        if(empty($ret)){
            return false;
        }
        else{
            #print_r($ls);

            if (isset($ret)){
                foreach($ret as $rec)
                {
                    if ($rec['name'] == $vpcname){
                        $nets = $rec['vxnet'];
                        foreach($nets as $net){
                            if($net['vxnet_network'] == "192.168.".$subnetaddr.".0/24"){
                                return true;
                            }
                        }
                        break;
                    }else{
                    }
                }
            }
        }
        return false;
    }

    //������port������������������
    public function check_port_exist($vpcname, $port, $username, $passwd){
        $port=array();
        $url = 'vpc?where=name=="' . $vpcname . '"';

        $rets = $this->get_url_items($url, $username, $passwd);
        $ret = $rets['_items'];

        if(empty($ret)){
            return false;
        }
        else{
            #print_r($ls);
            if (isset($ret)){
                foreach($ret as $rec)
                {
                    if ($rec['name'] == $vpcname){

                        $inports = $rec['access_control_inside'];
                        foreach ($inports as $inport){
                            if ($inport['dest_port'] == $port){
                                return true;
                            }
                        }
                        break;
                    }else{
                    }
                }
            }
        }

        return false;
    }

    public function get_vpc_list($region,$username,$password){
        $vpc=array();
        $url = 'vpc/?where="region"=="'.$region.'"';
        $rets = $this->get_url_items($url,$username,$password);
        $vpclist = $rets['_items'];
        if (is_array($vpclist)){
            foreach($vpclist as $rec)
            {
                if($rec['status']=='active'){
                    $nets = $rec['vxnet'];
                    foreach($nets as $net){
                        $vpc[$rec['name']][]=$net['vxnet_name'];
                    }
                }
            }
        }
        return $vpc;
    }
    //get harddisk info
    public function get_hd_list($region,$username,$password){
        $hd=array();
        $url = 'hard_disk/?where="region"=="'.$region.'"';
        $rets = $this->get_url_items($url,$username,$password);
        $hd_list = $rets['_items'];
        if (is_array($hd_list)){
            foreach($hd_list as $rec)
            {
                $hd[] = $rec['name'];
            }
        }
        return $hd;
    }
    //end
    
    

    public function get_vpc_url($vpcname, $username, $passwd){

        $url = 'vpc/?where="name"=="'.$vpcname.'"';
        $rets = $this->get_url_items($url, $username, $passwd);

        $ret = $rets['_items'];

        return $ret[0]['_id'];
    }
    
     public function get_hd_url($region="qingcloud_pek2",$hdname, $username, $passwd){

        //$url = 'hard_disk/?where="name"=="'.$hdname.'"';
        $url = 'hard_disk/?where={"region":"'.$region.'","name":"'.$hdname.'"}';
        $rets = $this->get_url_items($url, $username, $passwd);

        $ret = $rets['_items'];

        return $ret[0]['_id'];
    }
    
     public function get_hd_info($region="qingcloud_pek2",$hdname, $username, $passwd){

        //$url = 'hard_disk/?where="name"=="'.$hdname.'"';
        $url = 'hard_disk/?where={"region":"'.$region.'","name":"'.$hdname.'"}';
        $rets = $this->get_url_items($url, $username, $passwd);

        $ret = $rets['_items'];

        return $ret;
    }
    

    public function send_deploy_curl($username , $passwd, $region, $order_form, $eip, $vpc, $app)
    {
        $url = $this->urlbase . 'deploy';
        $auth = base64_encode($username . ':' . $passwd);

        $param = array(
            'username'=>$username,
            'password'=>$passwd,
            'order_form'=>"".$order_form
        );
        $cmd_list = array();
        if (isset($eip )){
            foreach($eip as $key => $eip_info){
                $cmd_list[]= array(
                    'url'=>'public_ip',
                    'cmd'=>'post',
                    'params'=>array(
                        'username'=>$username,
                        'name'=>$eip_info['eip_name'],
                        'bandwidth'=>(int)$eip_info['bandwidth'],
                        'region'=>$region
                    )
                );
            }
        }

        if(isset($vpc)){
            foreach($vpc as $result){
                $cmd_list[]= $result;
            }
        }

        foreach($app as $app_deploy_config){
            $cmd_list[] =$app_deploy_config;
        }

        $param['cmd_list']=$cmd_list;

        $ret = $this->curl->post($url, $param, array(), '', $auth);
        print_r(json_encode($param));
    }

    public function register_user($username, $passwd)
    {
        //$curl = new Curl;
        $url = $this->urlbase . 'accounts';

        $param = array("username"=>$username,
            "password"=>$passwd);

        $auth = base64_encode(DEPLOY_ADMIN . ':' . DEPLOY_SECRET);

        $ret = $this->curl->post($url, $param, array(), '', $auth);
    }

    public function change_password($user_name, $passwd){
        $passwd=md5($passwd);
        $url = $this->urlbase.'accounts';

        $auth = base64_encode(DEPLOY_ADMIN . ':' . DEPLOY_SECRET);

        $url = $this->urlbase.'accounts?where=username=="' . $user_name  .'"';
        $ret = $this->curl->get($url, array(), '', $auth);
        $rets = json_decode($ret, true);
        //print_r($rets);

        //only one account will return
        $item = $rets['_items'][0];

        $param = array(
            "updates" =>array(
                "action" =>"replace",
                "path"=> "password",
                "value"=>$passwd
            ),
        );

        $url = $this->urlbase.'deploy';

        $cmd_list = array(array(
            "url"=>"accounts/" . $item['_id'],
            "cmd"=>"patch",
            "params"=>$param
        ));


        $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "customer WHERE LOWER(email) = '" . $this->db->escape(utf8_strtolower($user_name)) . "'");

        $customer_info=$query->row;


        $params = array('username'=>$user_name,
            'order_form' => 'account_' . $item['_etag'] . rand(100000, 999999),
            'password' => $customer_info['password_plain'],
            'cmd_list' => $cmd_list
        );

        //print_r($params);
        $auth = base64_encode($user_name . ':' . $customer_info['password_plain']);
        $ret = $this->curl->post($url, $params, array(), '', $auth);

//        print_r($ret);
//        exit;
        return $ret;



    }

    public function get_price(){
        $url = $this->urlbase.'price';
        $username = DEPLOY_ADMIN;
        $passwd = DEPLOY_SECRET;
        $auth = base64_encode($username . ':' . $passwd);

        $ret = $this->curl->get($url, array(), '', $auth);
        $rets = json_decode($ret, true);
        $this->price = $rets['_items']['0'];
    }

    public function get_eip_price(){
        if (empty($this->error)){
            $this->get_price();
        }
        $eips = $this->price['hardware']['eip'];
        $eip_info=end($this->session->data['app']['eip']);
        $bandwidth = $eip_info['bandwidth'];

        foreach($eips as $eip){
            if ($eip['bandwidth'] == $bandwidth){
                return $eip['price'];
            }
        }

        return 65535;
    }

    public function get_vpc_price(){
        if (empty($this->error)){
            $this->get_price();
        }

        $vpcs = $this->price['hardware']['vpc'];

        $vpc_info=end($this->session->data['app']['vpc']);
        $vpctype = $vpc_info['vpc_type'];

        foreach($vpcs as $vpc){
            if ($vpc['vpc_type'] == $vpctype){
                return $vpc['price'];
            }
        }
        return 65535;
    }

    public function get_instance_price(){
        if (empty($this->error)){
            $this->get_price();
        }

        $insts = $this->price['hardware']['instance'];

        $ostype = 'linux';
        $cmtype = $this->request->post['type_name'];
        foreach($insts as $inst){
            if ($inst['os_type'] == $ostype){
                $instps = $inst['instance_type'];
                foreach($instps as $instp){

                    if($instp['type_name'] == $cmtype){
                        $eip_price=$this->get_eip_price();
                        $eip_price=$this->get_vpc_price();
                        echo ($instp['price']+$eip_price+$eip_price)/100;
                        exit;
                    }
                }
            }
        }
        echo "65535";
    }

    public function get_software_price(){
    }

    public function recharge($user_name, $passwd,$amount){
        $auth = base64_encode(DEPLOY_ADMIN . ':' . DEPLOY_SECRET);
        $url = $this->urlbase.'accounts?where=username=="' . $user_name.'"';
        $ret = $this->curl->get($url, array(), '', $auth);
        $rets = json_decode($ret, true);
        $item = $rets['_items'][0];

        $url = $this->urlbase.'deploy';
        $param = array(
            "updates" =>array(
                "action" =>"add",
                "path"=> "charge",
                "value"=>"{'money':".$amount.",'type':'store'}"
            ),
        );

        $cmd_list = array(array(
            "url"=>"accounts/" . $item['_id'],
            "cmd"=>"patch",
            "params"=>$param
        ));
        $params = array(
            'username'=>DEPLOY_ADMIN,
            'order_form' => 'account_' . $item['_etag'] . rand(100000, 999999),
            'password' => DEPLOY_SECRET,
            'cmd_list' => $cmd_list
        );
        //print_r($params);
        $auth = base64_encode($user_name . ':' . $passwd);



        $ret = $this->curl->post($url, $params, array(), '', $auth);
    }

    public function getbalance($user_name){
        $auth = base64_encode(DEPLOY_ADMIN . ':' . DEPLOY_SECRET);
        $value='{'.urlencode('"username":"'.$user_name.'"').'}';

        $url = $this->urlbase.'accounts?where='.$value;
        $ret = $this->curl->get($url, array(), '', $auth);
        $rets = json_decode($ret, true);

        $item = $rets['_items'][0];



        if(isset($item['consume'])){
            return sprintf("%.2f", $item['charge']-$item['consume']);

        }else{
            return $item['charge'];

        }
    }


    public function getquotas($user_name,$region){
        $auth = base64_encode(DEPLOY_ADMIN . ':' . DEPLOY_SECRET);
        $url = $this->urlbase.'accounts?where=username=="' . $user_name.'"';
       // $url = $this->urlbase.'accounts?where={"region":"'.$region.'","username":"'.$user_name.'"}';
        
        $ret = $this->curl->get($url, array(), '', $auth);
        $rets = json_decode($ret, true);
        $item = $rets['_items'][0];

        if(isset($item['quotas'])){
            foreach($item['quotas']['quota_reserveds'] as $result){
                $quota_reserveds[$result['region']]=$result;
                unset($quota_reserveds[$result['region']]['region']);
            }

            foreach($item['quotas']['quota_useds'] as $result){
                $quota_useds[$result['region']]=$result;
                unset($quota_useds[$result['region']]['region']);
            }
            foreach($item['quotas']['quota_limits'] as $result){
                $quota_limits[$result['region']]=$result;
                unset($quota_limits[$result['region']]['region']);
            }

            foreach($quota_reserveds[$region] as $key =>$value){
                $total[$key]=$quota_limits[$region][$key]-($quota_reserveds[$region][$key]+$quota_useds[$region][$key]);
            }

            return $total;
        }else{
            return false;
        }
    }

    public function getUsedquotas($user_name,$region){
        $auth = base64_encode(DEPLOY_ADMIN . ':' . DEPLOY_SECRET);
        $url = $this->urlbase.'accounts?where=username=="' . $user_name.'"';
        //$url = $this->urlbase.'accounts?where={"region":"'.$region.'","username":"'.$user_name.'"}';
        $ret = $this->curl->get($url, array(), '', $auth);
        $rets = json_decode($ret, true);
        $item = $rets['_items'][0];

        if(isset($item['quotas'])){
            foreach($item['quotas']['quota_reserveds'] as $result){
                $quota_reserveds[$result['region']]=$result;
                unset($quota_reserveds[$result['region']]['region']);
            }

            foreach($item['quotas']['quota_useds'] as $result){
                $quota_useds[$result['region']]=$result;
                unset($quota_useds[$result['region']]['region']);
            }

            foreach($quota_reserveds[$region] as $key =>$value){
                $total[$key]=$quota_reserveds[$region][$key]+$quota_useds[$region][$key];
            }

            return $total;
        }else{
            return false;
        }
    }
    public function getquotalimits($user_name,$region){
        $auth = base64_encode(DEPLOY_ADMIN . ':' . DEPLOY_SECRET);
        $url = $this->urlbase.'accounts?where=username=="' . $user_name.'"';
        //$url = $this->urlbase.'accounts?where={"region":"'.$region.'","username":"'.$user_name.'"}';
        $ret = $this->curl->get($url, array(), '', $auth);
        $rets = json_decode($ret, true);
        $item = $rets['_items'][0];


        if(isset($item['quotas'])){
            foreach($item['quotas']['quota_limits'] as $result){
                $quota_limits[$result['region']]=$result;
            }

            return $quota_limits[$region];
        }else{
            return false;
        }
    }

    public function  createRandomStr(){
        $str1 = '0123456789';//62个字符
        $str2 = 'abcdefghijklmnopqrstuvwxyz';//62个字符
        $str3 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';//62个字符

        $str1 = str_shuffle($str1);
        $str2 = str_shuffle($str2);
        $str3 = str_shuffle($str3);
        $str=substr($str1,0,3).substr($str2,0,3).substr($str3,0,3);
        $str=str_shuffle($str);

        return $str;
    }


}
?>